﻿using GameMap;
using QxFramework.Core;
using System;
using UnityEngine;
using UnityEngine.UI;

public class CombineUI : UIBase
{
    public string UserName = "";
    public string BenchName = "";
    public override void OnDisplay(object args)
    {
        base.OnDisplay(args);
        var strings = args as CombineUIArgs;
        UserName = strings.user;
        BenchName = strings.benchName;
        if (strings.benchName.StartsWith("Final") == true)
        {
            this.transform.Find("ObjectPanel").gameObject.SetActive(false);
            this.transform.Find("ObjectPanel").Find("FinalObjectPanel").gameObject.SetActive(true);
        }
        else
        {
            this.transform.Find("ObjectPanel").gameObject.SetActive(true);
            this.transform.Find("ObjectPanel").Find("FinalObjectPanel").gameObject.SetActive(false);
        }
       /* this.transform.Find("OperationPanel").Find("Bag").gameObject.SetActive(strings.benchName.StartsWith("Final"))*/;
    }
    public static CombineUI Instance;
    StateMachine sm = null;
    public GameObject draggingObj;
    public GameObject paramPanel;
    private void OnEnable()
    {
        sm = null;
        Instance = this;
        draggingObj = transform.Find("DraggingImage").gameObject;
        draggingObj.SetActive(false);
        paramPanel = transform.Find("ParamPanel").gameObject;
        paramPanel.SetActive(true);
        MessageManager.Instance.Get<ItemMapEvent>(false).RegisterHandler(ItemMapEvent.DeleteInBench, (object sender, EventArgs e) =>
         {
             ChangeSelectedObject(null);
             return null;
         });
    //    paramPanel.GetComponent<ParamPanel>().Init(null);
    }
    private void Update()
    {
        if (InputManager.Instance.GetKeyUp(KeyCode.Mouse0))
        //  ||      RectTransformUtility.RectangleContainsScreenPoint(transform.GetComponent<RectTransform>(),InputManager.Instance.MousePosition)==false)
        {
            InputManager.Instance.SetStateMachineTriger(StateMachineEvent.UI_LoseMouseControl);
            //          Debug.Log("Lose Control");
        }
        if (InputManager.Instance.GetKeyDown(KeyCode.Mouse0))
        //  ||      RectTransformUtility.RectangleContainsScreenPoint(transform.GetComponent<RectTransform>(),InputManager.Instance.MousePosition)==false)
        {
      //      AudioControl.Instance.PlaySound("Mouse");
        }
        //    Debug.Log(CombineUI.Instance.transform.GetComponentInChildren<ObjectPanel>().BenchItemList[0].Item2);
    }
    public void ChangeSelectedObject(Tuple<GameObject, CombinableItemField> info)
    {
        if (sm != null)
        {
            StateManager.Instance.Destory(sm);

        }
        if (info != null && info.Item1 != null && info.Item2 != null)
        {
            AudioControl.Instance.PlaySound("Mouse");
            sm = StateManager.Instance.CreateStateMachine<SelectedUI, BagUIStateMachine>(null, info);
        }
    }

    protected override void OnClose()
    {
        base.OnClose();
        if (sm != null)
        {
            StateManager.Instance.Destory(sm);
            sm = null;
        }
    }
    private void OnDestroy()
    {
        if (sm != null)
        {
            StateManager.Instance.Destory(sm);
            sm = null;
        }
        Instance = null;
    }
    private void OnDisable()
    {
        if (sm != null)
        {
            StateManager.Instance.Destory(sm);
            sm = null;
        }
        //   Instance = null;
    }
    public class BagUIStateMachine : StateMachine
    {
        public Tuple<GameObject, CombinableItemField> EditingInfo;
        public override void Start(object info)
        {
            base.Start(info);
            EditingInfo = info as Tuple<GameObject, CombinableItemField>;
            //        if (EditingInfo==null) return;
            EditingInfo.Item1.GetComponent<Image>().color = Color.gray;//.sprite = Resources.Load<Sprite>("Texture/UI/SelectedButtonBackground");
                                                                       //      if (EditingInfo.Item2 == null) return;
        }

        public override void Exit()
        {
            base.Exit();
            //   if (EditingInfo == null) return;
            //     CombineUI.Instance.draggingObj.SetActive(false);
            EditingInfo.Item1.GetComponent<Image>().color = Color.white;//.sprite = Resources.Load<Sprite>("Texture/UI/UnselectedButtonBackground");
        }
    }
    public class MouseUpUI : StateBase
    {
        internal override Type AnyButton()
        {
            return typeof(NormalUI);
        }
        public override void Start(object info)
        {
            base.Start(info);
            var obj = info as GameObject;
            var edting = (rootMachine as BagUIStateMachine).EditingInfo;
            
            if (obj == null)
            {
                //背包到背包
                if ((rootMachine as BagUIStateMachine).EditingInfo.Item2.BelongingType == ItemBelongingType.Bag)
                {

                    return;
                }
                //拼装台到背包
                else
                {
                    var field = (rootMachine as BagUIStateMachine).EditingInfo.Item2;
                    MessageManager.Instance.Get<ItemMapEvent>().DispatchMessage(ItemMapEvent.BenchToBag, this, new ItemMapArgs
                    {
                        User = field.User,
                        ItemName = field.ItemName
                    });
                    edting.Item1.GetComponent<Image>().color = Color.white;//.sprite = Resources.Load<Sprite>("Texture/UI/UnselectedButtonBackground");
                    edting = new Tuple<GameObject, CombinableItemField>(CombineUI.Instance.GetComponentInChildren<BagObjectPanel>().BagItemsList[0].Item1, edting.Item2);
                    edting.Item1.GetComponent<Image>().color = Color.gray;//.sprite = Resources.Load<Sprite>("Texture/UI/SelectedButtonBackground");
                }
            }
            //到拼装台
            else
            {
                var field = (rootMachine as BagUIStateMachine).EditingInfo.Item2;
                var s = obj.name.Split('_');
                if (field.BelongingType == ItemBelongingType.Bench)
                {

                    MessageManager.Instance.Get<ItemMapEvent>().DispatchMessage(ItemMapEvent.BenchToBag, this, new ItemMapArgs
                    {
                        User = field.User,
                        ItemName = field.ItemName,
                        //      ValuePos = new Vector3Int(int.Parse(s[1]), int.Parse(s[2]), 1),
                    });
                }
                var args = new ItemMapArgs
                {
                    User = field.User,
                    ItemName = field.ItemName,
                    MeshTransform = field.MeshTransform

                };
                args.MeshTransform.BenchMeshPos = new Vector3Int(int.Parse(s[1]), int.Parse(s[2]), 1);
             //   if((rootMachine as BagUIStateMachine).EditingInfo.Item2.BelongingType == ItemBelongingType.Bag || args.MeshTransform.BenchMeshPos!=edting.Item2.MeshTransform.BenchMeshPos)
               // {
                    AudioControl.Instance.PlaySound("装备拖拽放入槽内的声音");
                //}
                MessageManager.Instance.Get<ItemMapEvent>().DispatchMessage(ItemMapEvent.BagToBench, this, args);
                edting.Item1.GetComponent<Image>().color = Color.white; // = Resources.Load<Sprite>("Texture/UI/UnselectedButtonBackground");
                edting = new Tuple<GameObject, CombinableItemField>(obj, edting.Item2);
                edting.Item1.GetComponent<Image>().color = Color.gray;//.sprite = Resources.Load<Sprite>("Texture/UI/SelectedButtonBackground");
            }
            (rootMachine as BagUIStateMachine).EditingInfo = edting;
        }
    }

    public class NormalUI : StateBase
    {
        Tuple<GameObject, CombinableItemField> itemInfo;

        public override void Start(object info)
        {
            base.Start(info);
            itemInfo = (rootMachine as BagUIStateMachine).EditingInfo;
            itemInfo.Item1.transform.Find("Image").GetComponent<Image>().color = Color.white;
            if (itemInfo.Item2.BelongingType == ItemBelongingType.Bench)
            {
                CombineUI.Instance.paramPanel.GetComponent<ParamPanel>().Init(itemInfo.Item2);
            }
        }
        public override object Exit()
        {
            CombineUI.Instance.paramPanel.GetComponent<ParamPanel>().Init(null);
            return null;
        }
    }
    public class SelectedUI : StateBase
    {
        public GameObject GetPreview(GameObject DraggingObj)
        {
            if (RectTransformUtility.RectangleContainsScreenPoint(CombineUI.Instance.transform.Find("ObjectPanel").GetComponent<RectTransform>(),
               InputManager.Instance.MousePosition) == false)
            {
                foreach (var x in CombineUI.Instance.transform.GetComponentInChildren<ObjectPanel>().BenchItemList)
                {

                    if (x.Item2 != null && x.Item2 != (rootMachine as BagUIStateMachine).EditingInfo.Item2) continue;
                    x.Item1.transform.Find("Image").GetComponent<Image>().color = Color.white;
                    x.Item1.transform.Find("Image").GetComponent<Image>().sprite = null;
                }
                return null;
            }
            GameObject ans = null;
            float dis = float.MaxValue;
            foreach (var x in CombineUI.Instance.transform.GetComponentInChildren<ObjectPanel>().BenchItemList)
            {

                if (x.Item2 != null && x.Item2 != (rootMachine as BagUIStateMachine).EditingInfo.Item2) continue;
                if (Vector2.Distance(InputManager.Instance.MousePosition, x.Item1.transform.position) < dis)
                {
                    dis = Vector2.Distance(InputManager.Instance.MousePosition, x.Item1.transform.position);
                    ans = x.Item1;
                }
                x.Item1.transform.Find("Image").GetComponent<Image>().color = Color.white;
                x.Item1.transform.Find("Image").GetComponent<Image>().sprite = null;
            }
            if (ans != null)
            {
                ans.transform.Find("Image").GetComponent<Image>().color = new Color(0, 0, 0, 255);
                ans.transform.Find("Image").GetComponent<Image>().sprite = CombineUI.Instance.draggingObj.GetComponent<Image>().sprite;
                ans.transform.eulerAngles = CombineUI.Instance.draggingObj.GetComponent<Image>().transform.eulerAngles;
                ans.transform.localScale = CombineUI.Instance.draggingObj.GetComponent<Image>().transform.localScale;
            }
            return ans;
        }
        public override void FixedUpdate()
        {
            base.FixedUpdate();
            CombineUI.Instance.draggingObj.transform.position = InputManager.Instance.MousePosition;
            if (CombineUI.Instance.draggingObj.activeSelf)
            {
                GetPreview(CombineUI.Instance.draggingObj);
            }
        }
        public override object Exit()
        {
            CombineUI.Instance.draggingObj.SetActive(false);
            return GetPreview(CombineUI.Instance.draggingObj);
        }
        public override void Start(object info)
        {
            base.Start(info);

            CombineUI.Instance.draggingObj.SetActive(true);
            CombineUI.Instance.draggingObj.GetComponent<Image>().sprite =
               GameControl.GameManager.Get<GameControl.IItemInstantiateManager>().GetItemSettingByName((rootMachine as BagUIStateMachine).EditingInfo.Item2.ItemName.Split('_')[0]).GetComponentInChildren<SpriteRenderer>().sprite;
            var trans = (rootMachine as BagUIStateMachine).EditingInfo.Item2.MeshTransform;
            CombineUI.Instance.draggingObj.transform.eulerAngles = new Vector3(CombineUI.Instance.draggingObj.transform.eulerAngles.x, CombineUI.Instance.draggingObj.transform.eulerAngles.y, trans.MeshRotate * 90);
            CombineUI.Instance.draggingObj.transform.localScale = new Vector3(trans.IsFlipedInMesh ? -1 : 1, 1, 1);
        }
        [Bind(StateMachineEvent.UI_LoseMouseControl)]
        Type MouseUp()
        {
            return typeof(MouseUpUI);
        }
    }

}